package com.gogowan.agroenterprise.newview;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Debug;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.android.volley.Request;
import com.android.volley.manager.LoadController;
import com.android.volley.manager.RequestManager;
import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MsgType;
import com.gogowan.agroenterprise.model.CheckRequest;
import com.gogowan.agroenterprise.model.CheckResult;
import com.gogowan.agroenterprise.model.CheckScanResult;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.utils.GdLocationUtil;
import com.gogowan.agroenterprise.utils.ToastUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.MyProgressDialog;
import com.ioid.utils.JsonUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2018/8/21.
 */

public class Commodity_Inspection_Activity extends BaseActivity implements RequestManager.RequestListener {
    @BindView(R.id.all_top_back_btn)
    ImageView allTopBackBtn;
    @BindView(R.id.all_top_right_btn)
    Button allTopRightBtn;
    @BindView(R.id.all_top_title)
    TextView allTopTitle;
    @BindView(R.id.commodity_Order_no_tv)
    TextView commodityOrderNoTv;
    @BindView(R.id.commodity_shop_name_tv)
    TextView commodityShopNameTv;
    @BindView(R.id.commodity_area_tv)
    TextView commodityAreaTv;
    @BindView(R.id.commodity_normal_Rb)
    RadioButton commodityNormalRb;
    @BindView(R.id.commodity_abnormal_Rb)
    RadioButton commodityAbnormalRb;
    @BindView(R.id.commodity_dealers_Et)
    EditText commodityDealersEt;
    @BindView(R.id.commodity_save_Tv)
    TextView commoditySaveTv;
    @BindView(R.id.commodity_dealers_ll)
    LinearLayout commodityDealersLl;
    @BindView(R.id.commodity_region_name_tv)
    TextView commodityRegionNameTv;
    private int StationCode = 0;
    private CheckScanResult result;
    private LoginResultInfo info;
    private String resultString;
    private MyProgressDialog progressDialog;
    private LoadController mLoadController = null;
    private static final int Save = 0;
    private static int MY_PERMISSIONS_LOCATION = 1590;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_inspection);
        ButterKnife.bind(this);
        initValue();
    }

    private void initValue() {
        allTopTitle.setText("商品稽查");
        allTopBackBtn.setVisibility(View.VISIBLE);
        progressDialog = new MyProgressDialog(Commodity_Inspection_Activity.this, "");
        resultString = getIntent().getStringExtra("resultString");
        result = (CheckScanResult) getIntent().getSerializableExtra("CheckScanResult");
        info = (LoginResultInfo) getIntent().getSerializableExtra("info");
        if (result == null) {
            showToast("数据获取失败");
            return;
        }
        getCameraPerisson();
        commodityOrderNoTv.setText(result.getOutNo());
        commodityShopNameTv.setText(result.getDealerName());
        commodityNormalRb.performClick();
        commodityRegionNameTv.setText(result.getMainArea());
    }

    /**
     * 获取定位权限
     */
    public void getCameraPerisson() {
        if (ContextCompat.checkSelfPermission(Commodity_Inspection_Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            new AlertDialog.Builder(this).setTitle("提示").setMessage("请同意定位权限，否则将无法不被允许提交数据").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(Commodity_Inspection_Activity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_LOCATION);
                }
            }).show();
        } else {
            getLocationString();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_LOCATION) {
            getCameraPerisson();
        }
    }

    private void getLocationString() {
        GdLocationUtil.init(this).setOnResultListener(new GdLocationUtil.MyLocationListener() {

            @Override
            public void onResult(AMapLocation aMapLocation) {
                commodityAreaTv.setText(aMapLocation.getAddress());
            }
        }).start();
    }

    @OnClick({R.id.all_top_back_btn, R.id.commodity_normal_Rb, R.id.commodity_abnormal_Rb, R.id.commodity_save_Tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.all_top_back_btn:
                finish();
                break;
            case R.id.commodity_normal_Rb:
                StationCode = 1;
                commodityDealersLl.setVisibility(View.GONE);
                break;
            case R.id.commodity_abnormal_Rb:
                StationCode = 0;
                commodityDealersLl.setVisibility(View.VISIBLE);
                break;
            case R.id.commodity_save_Tv:
                if (!Debug.isDebuggerConnected()&&commodityAreaTv.getText().toString().length() < 1) {
                    showToast("未获取到定位信息，无法提交数据");
                    return;
                }
                if (!Debug.isDebuggerConnected()&&commodityRegionNameTv.getText().toString().length() < 1) {
                    showToast("未获取到定位信息，无法提交数据");
                    return;
                }
                http();
                break;
        }
    }

    private void http() {

        CheckRequest request = new CheckRequest();
        request.setOutNo(result.getOutNo());
        request.setProductCode(result.getProductCode());
        request.setDealerId(result.getDealerId());
//        request.setEnterpriseId(info.getEnterpriseinfo().getEnterpriseid());
//        request.setUserType(info.getEnterpriseinfo().getUserType());
        request.setDealerName(result.getDealerName());
        request.setUserId(MyApplication.mSettings.getLong("personid",0));
//        request.setUserName(info.getUserinfo().getUsername());
        request.setAddress(commodityAreaTv.getText().toString());
        request.setStatus(StationCode);
        request.setMaterialId(result.getMaterialId());
        request.setMaterialName(result.getMaterialName());
        request.setXDealerName(commodityDealersEt.getText().toString());
        request.setRemark(commodityDealersEt.getText().toString());
//        if (StationCode == 0 && request.getXDealerName().length() < 1) {
//            showToast("请输入当前所在经销商");
//            return;
//        }
        String messageStr = Utils.getPostRequest(request, MsgType.Temp.Check.getValue());
        progressDialog.setCancelable(false);
        progressDialog.setLoadingText("正在提交" + "\n"
                + getString(R.string.prompt_progress_wait));
        progressDialog.show();
        Map<String,String>map=new HashMap<>();
        map.put("X-Access-Token", MyApplication.mSettings.getString("token",""));
        mLoadController = RequestManager.getInstance().request(Request.Method.POST,getString(R.string.first_url)
                        + getString(R.string.insertCheckRecord),
                messageStr, map,Commodity_Inspection_Activity.this,false,
                600*1000, 1, Save);
    }

    @Override
    public void onRequest() {

    }

    @Override
    public void onSuccess(String response, Map<String, String> headers, String url, int actionId) {
        progressDialog.dismiss();
        try {
            JSONObject jo=new JSONObject(response);
            if(jo.getInt("code")!=200){
                ToastUtils.show(getApplicationContext(),jo.getString("msg"));
                return;
            }
            ShowDialog("提示", result.getResultinfo(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    setResult(Utils.save_Result_Code);
                    finish();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            ToastUtils.show(getApplicationContext(),"数据解析失败");
        }


    }


    @Override
    public void onError(String errorMsg, String url, int actionId) {
        progressDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadController != null) {
            mLoadController.cancel();
            mLoadController = null;
        }
        if (progressDialog != null) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }
}
